package com.itheima.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class UserController {

    @RequestMapping("/quick1")
    public String save1(){
        System.out.println("Controller running...");
        return "success";
    }

    @RequestMapping("/quick2")
    public ModelAndView save2(){
        //Model:模型   作用是封装数据
        //View:视图    作用是展示数据
        ModelAndView modelAndView = new ModelAndView();
        //设置模型数据
        modelAndView.addObject("label","奥特曼");
        //设置视图名称
        modelAndView.setViewName("success.jsp");
        return modelAndView;
    }

    @RequestMapping("/quick3")
    public ModelAndView save3(ModelAndView modelAndView){
        modelAndView.addObject("label","奥特曼");
        modelAndView.setViewName("success.jsp");
        return modelAndView;
    }

    @RequestMapping("/quick4")
    public String save4(Model model){
        model.addAttribute("label","大大怪将军");
        return "success";
    }




    @RequestMapping("/quick5")
    public String save5(HttpServletRequest req){
        req.setAttribute("label","小小怪下士");
        return "success";
    }


    @RequestMapping("/quick6")
    @ResponseBody
    public String save6() throws IOException {
        User user=new User();
        user.setUsername("zhangsan");

        ObjectMapper objectMapper=new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);

        return json;
    }



    @RequestMapping("/quick7")
    @ResponseBody
    public User save7() throws IOException {
        User user=new User();
        user.setUsername("zhangsan");

        return user;
    }



    @RequestMapping("/quick8")
    @ResponseBody
    public void save8(String username, MultipartFile uploadFile) throws IOException {
        System.out.println(username);
        //获得上传文件名称
        String originalFilename = uploadFile.getOriginalFilename();
        //保存文件...
        uploadFile.transferTo(new File("C:\\"+originalFilename));
    }
}
